<!--
 * @Description: 销量排行模块 组件
 * @Author: zhihong deng
 * @Date: 2021-07-04 16:39:19
 * @LastEditors: zhihong deng
 * @LastEditTime: 2021-07-10 22:21:41
-->
<template>
  <div class="com-container">
    <div class="com-chart" ref="rank_ref"></div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  data () {
    return {
      chartInstance: '',
      allData: '',
      startValue: 0,//区域缩放的起点值
      endValue: 9,//区域缩放的终点值
      timerId: null,//定时器的标识
    }
  },
  computed: {
      ...mapState(['theme'])
    },
    watch: {
      theme () {
        // 第一步：销毁当前图表
        this.chartInstance.dispose()
        // 第二步：重新以最新的主题初始化图表对象
        this.initChart()
        // 第三步：完成屏幕的适配
        this.screenAdapter()
        // 第四步：更新图表的展示
        this.updateChart()
      }
    },
  methods: {
    // 初始化图表
    initChart () {
      this.chartInstance = this.$echarts.init(this.$refs.rank_ref,this.theme);
      const initOption = {
        title: {
          text: '▎地区销量排行',
          left: 20,
          top: 20,
        },
        grid: {
          top: '40%',
          left: '5%',
          right: '5%',
          bottom: '5%',
          containLabel: true,//是否包含标签文字
        },
        tooltip: {
          show: true,
        },
        xAxis: {
          type: 'category',
        },
        yAxis: {
          type: 'value',
        },
        series: [
          {
            type: 'bar',
          }
        ],
      };
      this.chartInstance.setOption(initOption);
      // 鼠标移入取消定时器
      this.chartInstance.on('mouseover',()=>{
        clearInterval(this.timerId);
      })
      // 鼠标移出开启定时器
      this.chartInstance.on('mouseout',()=>{
        this.startInterval();
      })
    },
    // 获取数据
    getData (ret) {
      // 获取服务器的数据，对this.allData进行赋值之后，调用updataChart方法更新图表
      // const {data: ret} = await this.$http.get('rank');
      this.allData = ret;
      // 数据从大到小排列
      this.allData.sort( (a,b)=> {
        return b.value - a.value;
      });
      console.log('allData',this.allData);
      this.updataChart();
      this.startInterval();
    },
    // 更新图表
    updataChart () {
      const colorArr =[
        ['#0BA82C','#4FF778'],
        ['#2E72BF','#23E5E5'],
        ['#5052EE','#AB6EE5'],
        ]
      // 处理图表需要的数据
      // 所有省份所形成的数组
      const provinceArr = this.allData.map( item => {
        return item.name;
      })
      // 所有省份对应的销售金额
      const valueArr = this.allData.map( item => {
        return item.value;
      })
      const dataOption = {
        xAxis: {
          data: provinceArr,
        },
        dataZoom: {
          show: false,
          startValue: this.startValue,
          endValue: this.endValue,
        },
        series: [
          {
            data: valueArr,
            itemStyle: {
              color: arg => {
                let targetColorArr = null;
                if (arg.value > 300) {
                  targetColorArr = colorArr[0];
                } else if (arg.value > 200) {
                  targetColorArr = colorArr[1];
                } else {
                  targetColorArr = colorArr[2];
                }
                return new this.$echarts.graphic.LinearGradient(0,0,0,1,[
                  {
                    offset: 0,
                    color: targetColorArr[0],
                  },
                  {
                    offset: 1,
                    color: targetColorArr[1],
                  }
                ])
              }
            },
          }
        ]
      };
      this.chartInstance.setOption(dataOption);
    },
    // 分辨率适配
    screenAdapter () {
      const titleFontSize = this.$refs.rank_ref.offsetWidth / 100 * 3.6
      const adapterOption = {
        title: {
          textStyle: {
            fontSize: titleFontSize
          }
        },
        series: [
          {
            barWidth: titleFontSize,
            itemStyle: {
              barBorderRadius: [titleFontSize/2,titleFontSize/2,0,0],
            }
          }
        ]
      };
      this.chartInstance.setOption(adapterOption);
      this.chartInstance.resize();
    },
    // 定时器
    startInterval () {
      // 如果有定时器，先取消在启动新的
      if (this.timerId) {
        clearInterval(this.timerId);
      }
      this.timerId = setInterval (() => {
        this.startValue++;
        this.endValue++;
        if (this.endValue > this.allData.length - 1) {
          this.startValue = 0;
          this.endValue = 9;
        }
        this.updataChart();
      },2000)
    },
  },
  created () {
    this.$socket.registerCallBack('rankData',this.getData)
  },
  mounted () {
    this.initChart();
    // this.getData();
    this.$socket.send({
      action: 'getData',
      socketType: 'rankData',
      chartName: 'rank',
      value: ''
    })
    window.addEventListener('resize',this.screenAdapter);
    this.screenAdapter();
  },
  destroyed () {
    window.removeEventListener('resize',this.screenAdapter);
    clearInterval(this.timerId);
    this.$$socket.unRegisterCallBack('rankData')
  },
}
</script>

<style>
</style>